package com.heima.gateway.filiters;


import com.alibaba.fastjson.JSON;
import com.heima.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Order(0)
@Component
@Slf4j
public class LoginFiliter implements GlobalFilter {
    private static List<String> urlList = new ArrayList<>();

    static {
        urlList.add("/login/in");
        urlList.add("/v2/api-docs");
    }


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求
        ServerHttpRequest request = exchange.getRequest();
        //获取当前请求路径，通过白名单判断是否要放行
        String path = request.getURI().getPath();
        for (String url : urlList) {
            if (path.contains(url)) {
                return chain.filter(exchange);
            }
        }
        //获取请求头
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");
        //判断请求头中携带的是否有token
        if (StringUtils.isBlank(token)) {
            //没有登录，不能放行
            return writeMessage(exchange, "请登录后再访问");
        }
        //解析token，判断token有无过期
        try {
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int i = AppJwtUtil.verifyToken(claims);
            if (i < 1) {//i<1说明token没有过期
                //取出token中的用户id
                Object id = claims.get("id");
                //将取出的用户id重新写入请求头中
                request.mutate().header("userId", String.valueOf(id));
                exchange.mutate().request(request);
                //打印日志
                log.info("自媒体用户登录成功 当前登录用户为 id ==> {}", id);
                return chain.filter(exchange);
            }
            log.error("解析token异常，当前token已过期");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("解析token异常 ===>{}", e.getMessage());
        }
        return writeMessage(exchange, "用户解析token异常");
    }

    private Mono<Void> writeMessage(ServerWebExchange exchange, String msg) {
        Map map = new HashMap<>();
        map.put("code", "401");
        map.put("errorMessage", msg);
        // 获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        // 设置响应状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        // 设置响应的数据格式
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        // 设置响应数据
        DataBuffer wrap = response.bufferFactory().wrap(JSON.toJSONBytes(map));
        // 响应数据
        return response.writeWith(Flux.just(wrap));
    }
}
